﻿using System;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Reflection;
using System.Xml.Linq;
using QuickPrompt.DomainModel;
using RedandBlue.Common.Logging;

namespace QuickPrompt.Helper
{
    public class EmailHelper
    {
        public SmtpSetting ReadSmtpForSiteId()
        {
            string configFile = "default.xml";
            var executingPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string absoluteFilePath = Path.Combine(executingPath, "resources", "smtp", configFile);
            if (string.IsNullOrEmpty(absoluteFilePath))
            {
                Log.Error(className: GetType().Name,
                       methodName: MethodBase.GetCurrentMethod().Name,
                       message: "Could not find the smtp settings file: {0}",
                       args: absoluteFilePath);

                return null;
            }
            XDocument xdoc = XDocument.Load(absoluteFilePath);
            var settings = (from ms in xdoc.Descendants("mailSettings")
                            let smtp = ms.Element("smtp")
                            let network = smtp.Element("network")
                            select new SmtpSetting
                            {
                                Host = network.Attribute("host").Value,
                                Port = Convert.ToInt32(network.Attribute("port").Value),
                                UserName = network.Attribute("userName").Value,
                                Password = network.Attribute("password").Value,
                                EmailFrom = smtp.Attribute("from").Value
                            }).FirstOrDefault();
            return settings;
        }

        public bool Send(MailMessage message)
        {
            SmtpSetting smtpSetting = ReadSmtpForSiteId();
            SmtpClient smtpClient = new SmtpClient
            {
                Host = smtpSetting.Host,
                Port = smtpSetting.Port,
                Credentials = new System.Net.NetworkCredential(smtpSetting.UserName, smtpSetting.Password),
                EnableSsl = false
            };
            message.From = new MailAddress(smtpSetting.EmailFrom);
            try
            {
                smtpClient.Send(message);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
